<template>
  <div class="tech-forum">
    <!-- 顶部导航栏 -->
    <NavBar />

    <!-- 主要内容区 -->
    <main class="forum-main">
      <div class="main-container">
        <div class="ask-post-container">
          <h2 class="ask-title">提问</h2>
          
          <!-- 问题标题 -->
          <div class="form-group">
            <label for="postTitle">问题标题</label>
            <input 
              id="postTitle" 
              v-model="postTitle" 
              type="text" 
              placeholder="请输入问题标题（简明扼要概括问题）" 
              class="form-control"
              @input="validateTitle"
            />
            <div class="error-message" v-if="titleError">{{ titleError }}</div>
          </div>
          
          <!-- 问题内容 -->
          <div class="form-group">
            <label for="postContent">问题描述</label>
            <textarea 
              id="postContent" 
              v-model="postContent" 
              placeholder="请详细描述您的问题（包括您遇到的问题、尝试过的解决方案等）" 
              class="form-control"
              rows="10"
              @input="validateContent"
            ></textarea>
            <div class="error-message" v-if="contentError">{{ contentError }}</div>
          </div>
          
          <!-- 标签选择 -->
          <div class="form-group">
            <label>选择标签（1-5个）</label>
            <div class="board-filter">
              <span 
                class="board" 
                v-for="board in boards" 
                :key="board.boardId"
                @click="toggleBoardSelection(board)"
                :class="{ selected: board.selected }"
              >
                {{ board.boardName }}
              </span>
            </div>
            <div class="error-message" v-if="boardError">{{ boardError }}</div>
          </div>
          
          <!-- 提交按钮 -->
          <div class="form-actions">
            <button 
              class="btn-primary" 
              @click="submitPost"
              :disabled="isSubmitting"
            >
              <span v-if="isSubmitting">提交中...</span>
              <span v-else>提交问题</span>
            </button>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getBoardListService} from '@/apis/board.js';
import { createPostService} from '@/apis/post.js';
import { ElMessage } from 'element-plus';
import { getToken } from '@/utils/cookie';
import { getUserInfoService } from '@/apis/user'
const router = useRouter();

// 表单数据
const postTitle = ref('');
const postContent = ref('');
const boards = ref([]);

// 验证错误
const titleError = ref('');
const contentError = ref('');
const boardError = ref('');

// 提交状态
const isSubmitting = ref(false);

// 获取标签列表
const fetchBoards = async () => {
  try {
    const res = await getBoardListService({
      pageNum: 1,
      pageSize: 100
    });
    boards.value = res.rows.map(board => ({
      ...board,
      selected: false
    }));
  } catch (error) {
    console.error('获取标签列表失败:', error);
    ElMessage.error('获取标签列表失败');
  }
};

// 切换标签选择
const toggleBoardSelection = (board) => {
  board.selected = !board.selected;
  boardError.value = '';
};

// 验证标题
const validateTitle = () => {
  if (!postTitle.value.trim()) {
    titleError.value = '请输入问题标题';
    return false;
  }
  if (postTitle.value.length > 100) {
    titleError.value = '标题不能超过100个字符';
    return false;
  }
  titleError.value = '';
  return true;
};

// 验证内容
const validateContent = () => {
  if (!postContent.value.trim()) {
    contentError.value = '请输入问题描述';
    return false;
  }
  if (postContent.value.length > 5000) {
    contentError.value = '内容不能超过5000个字符';
    return false;
  }
  contentError.value = '';
  return true;
};

// 验证标签
const validateBoards = () => {
  const selectedBoards = boards.value.filter(board => board.selected);
  if (selectedBoards.length === 0) {
    boardError.value = '请至少选择一个标签';
    return false;
  }
  if (selectedBoards.length > 5) {
    boardError.value = '最多选择5个标签';
    return false;
  }
  boardError.value = '';
  return true;
};

// 提交问题
const submitPost = async () => {
  if (!validateTitle() || !validateContent() || !validateBoards()) {
    return;
  }

  try {
    isSubmitting.value = true;
    const res = await getUserInfoService()
    const selectedBoards = boards.value
        .filter(board => board.selected)
        .map(board => String(board.boardId));+
    
    await createPostService({
      postTitle: postTitle.value,
      postContent: postContent.value,
      boards: selectedBoards.join(','),
      userId: res.data.userId
    });
    
    ElMessage.success('问题提交成功');
    router.push('/forum/layout');
  } catch (error) {
    console.error('提交问题失败:', error);
    ElMessage.error('提交问题失败');
  } finally {
    isSubmitting.value = false;
  }
};

onMounted(() => {
  fetchBoards();
});
</script>

<style scoped>
.tech-forum {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.forum-main {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 20px;
}

.main-container {
  display: flex;
  justify-content: center;
}

.ask-post-container {
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
  width: 100%;
  max-width: 800px;
}

.ask-title {
  margin: 0 0 28px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  text-align: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.form-group {
  margin-bottom: 28px;
}

.form-group label {
  display: block;
  margin-bottom: 10px;
  font-weight: 500;
  color: #333;
  font-size: 16px;
}

.form-control {
  width: 100%;
  padding: 14px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 15px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

textarea.form-control {
  min-height: 220px;
  resize: vertical;
  line-height: 1.6;
}

.error-message {
  margin-top: 8px;
  color: #dc3545;
  font-size: 14px;
  height: 18px;
}

.board-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.board {
  background: #f8f9fa;
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
  border: 1px solid #e0e0e0;
}

.board:hover {
  background: #e9ecef;
}

.board.selected {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.form-actions {
  margin-top: 32px;
  text-align: center;
}

.btn-primary {
  background: linear-gradient(135deg, #32C5FF 0%, #0095ff 100%);
  color: white;
  border: none;
  padding: 12px 32px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 160px;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 149, 255, 0.2);
}

.btn-primary:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .forum-main {
    padding: 16px;
  }
  
  .ask-post-container {
    padding: 24px 16px;
  }
  
  .ask-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
  
  .form-group {
    margin-bottom: 20px;
  }
  
  .board {
    padding: 6px 12px;
    font-size: 13px;
  }
  
  .btn-primary {
    padding: 10px 24px;
    font-size: 15px;
  }
}
</style>